package cn.com.shopec.erp.base.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.shopec.erp.base.dao.IProfitsCommodityDao;
import cn.com.shopec.erp.base.dao.IProfitsProductDao;
import cn.com.shopec.erp.base.dao.IProfitsProductHistoryDao;
import cn.com.shopec.erp.base.entity.ProfitsCommodity;
import cn.com.shopec.erp.base.entity.ProfitsProduct;
import cn.com.shopec.erp.base.entity.ProfitsProductHistory;
import cn.com.shopec.erp.base.service.IProfitsService;
import cn.com.shopec.erp.base.vo.ProfitsVo;
import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.LogicUtil;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.product.model.BenefitProduct;



@Service
public class ProfitsServiceImpl implements IProfitsService{
	
	@Resource
    private IProfitsProductDao profitsProductDao;
	@Resource
    private IProfitsProductHistoryDao profitsProductHisDao;
	
	@Resource
	private IProfitsCommodityDao profitsCommodityDao;
	
	@Override
	@Transactional
	public void addProfits(ProfitsVo vo,String profitlist) throws Exception {
		JSONArray jsonArray = JSONArray.fromObject(profitlist);
		String code = "";
		if(LogicUtil.isNotNullAndEmpty(jsonArray)){
			for(int i = 0;i<jsonArray.size(); i++){
				JSONObject proObject = jsonArray.getJSONObject(i);
				
				//先判断商品中是否存在，如有再对货品表进行判断
				 DetachedCriteria de = profitsCommodityDao.createCriteria();
				 de.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
				 de.add(Restrictions.eq("commodityCode", vo.getCommodityCode()));
				 List<ProfitsCommodity> comList = profitsCommodityDao.findByCriteria(de);
				 if(null != comList && comList.size()>0)
				 {
					//如存在，执行修改操作，反之新增操作
					 if(StringUtil.isExist(vo.getCode())){
						 code = vo.getCode();
					 }
					 String proCode = proObject.getString("prodNo");
					    DetachedCriteria detachedCriteria = profitsProductDao.createCriteria();
						detachedCriteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
						detachedCriteria.add(Restrictions.eq("code", code));
						detachedCriteria.add(Restrictions.eq("productCode", proCode));
						List<ProfitsProduct> proList = profitsProductDao.findByCriteria(detachedCriteria); 
						if(null != proList && proList.size()>0){
							ProfitsProduct pro = getProfitsProductByProductCode(proCode);
							/*try {
								pro.setProfits(Double.valueOf(proObject.getDouble("profits")));
							} catch (Exception e) {
								continue;
							}*/
							setProfitsParams(pro, proObject);
							pro.setProductCode(proCode);
							pro.setCode(code);
							profitsProductDao.update(pro);
							ProfitsProductHistory proHis = getLastHistory(pro, 0);
							if (proObject.getInt("enable") == 1) {
								 proHis.setCode(code);//code
								 proHis.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);//未删除
								 proHis.setProductCode(proObject.getString("prodNo"));//货品编号
								 setProfitsHisParams(proHis, proObject);
								 proHis.setProfitsProduct(pro);
								 profitsProductHisDao.update(proHis);
							} else {
								if (DateUtil.getCurrentMillis() > DateUtil.getMillis(DateUtil.parseDate(proHis.getValidTimeEnd() + " 23:59:59", DateUtil.TIMESTAMP_PATTERN)) && 
										!pro.getValidTimeStart().equals(proHis.getValidTimeStart())) {
									ProfitsProductHistory proH = new ProfitsProductHistory();
									proH.setCode(code);//code
									proH.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);//未删除
									proH.setProductCode(proObject.getString("prodNo"));//货品编号
									proH.setCreateTime(Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())));
									 setProfitsHisParams(proH, proObject);
									 proH.setProfitsProduct(pro);
									 profitsProductHisDao.save(proH);
								} else {
									proHis.setCode(code);//code
									 proHis.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);//未删除
									 proHis.setProductCode(proObject.getString("prodNo"));//货品编号
									 setProfitsHisParams(proHis, proObject);
									 proHis.setProfitsProduct(pro);
									 profitsProductHisDao.update(proHis);
								}
							}
						}else{
							ProfitsProduct profits = new  ProfitsProduct();
							profits.setCode(code);
							profits.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);
							/*try {
								if(StringUtil.isExist(String.valueOf(proObject.getDouble("profits")))){
									profits.setProfits(proObject.getDouble("profits"));//让利
								}
							} catch (Exception e) {
								continue;
							}*/
							setProfitsParams(profits, proObject);
							profits.setProductCode(proCode);//货品编码
							profitsProductDao.save(profits);
							ProfitsProductHistory proHis = new ProfitsProductHistory();
							 proHis.setCode(code);//code
							 proHis.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);//未删除
							 proHis.setProductCode(proObject.getString("prodNo"));//货品编号
							 proHis.setCreateTime(Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())));
							 setProfitsHisParams(proHis, proObject);
							 proHis.setProfitsProduct(profits);
							 profitsProductHisDao.save(proHis);
						}
				 }else{
					 //商品表
					 ProfitsCommodity comm = new ProfitsCommodity();
					 comm.setCode(SZSCMConstant.genUUID());//code
					 comm.setCommodityCode(vo.getCommodityCode());//商品编码
					 comm.setCommodityName(proObject.getString("commoName"));//商品名称
					 comm.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);//未删除
					 //货品表
					 code = comm.getCode();
					 ProfitsProduct product = new ProfitsProduct();
					 product.setCode(comm.getCode());//code
					 product.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);//未删除
					 product.setProductCode(proObject.getString("prodNo"));//货品编号
					 //product.setProfits(proObject.getDouble("profits"));//让利比例
					 setProfitsParams(product, proObject);
					 profitsProductDao.save(product);
					 profitsCommodityDao.save(comm); 
					 ProfitsProductHistory proHis = new ProfitsProductHistory();
					 proHis.setCode(comm.getCode());//code
					 proHis.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);//未删除
					 proHis.setProductCode(proObject.getString("prodNo"));//货品编号
					 proHis.setCreateTime(Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())));
					 setProfitsHisParams(proHis, proObject);
					 proHis.setProfitsProduct(product);
					 profitsProductHisDao.save(proHis);
				 }
			}
		}
		
		
	}
	
	@Override
	public ProfitsProductHistory getLastHistory(ProfitsProduct pro, int index) {
		DetachedCriteria criteria = profitsProductHisDao.createCriteria();
		criteria.add(Restrictions.eq("productCode", pro.getProductCode()));
		criteria.add(Restrictions.eq("code", pro.getCode()));
		criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
		criteria.addOrder(Order.desc("createTime"));
		List<ProfitsProductHistory> pphs = profitsProductHisDao.findByCriteria(criteria);
		ProfitsProductHistory pph = null;
		if (null != pphs && pphs.size() > 0) {
			if (index == 0) {
				pph = pphs.get(index);
			} else if (index == 1 && pphs.size() > 1) {
				pph = pphs.get(index);
			}
		}
		return pph;
	}

	/**
	 * 
	 * @MethodName setProfitsHisParams
	 * @Description 设置让利历史参数
	 * @author chengui
	 * @date 2013-7-4 下午5:01:27
	 * @param proHis
	 * @param proObject
	 */
	private void setProfitsHisParams(ProfitsProductHistory proHis,
			JSONObject proObject) {
		proHis.setBrandName(proObject.getString("brandName"));
		proHis.setBrandNo(proObject.getString("brandNo"));
		proHis.setCasePakgSize(proObject.getString("casePakgSize"));
		proHis.setCatName(proObject.getString("catName"));
		proHis.setCatNo(proObject.getString("catNo"));
		proHis.setCommoName(proObject.getString("commoName"));
		proHis.setCommoNo(proObject.getString("commoNo"));
		proHis.setInventoryType(proObject.getInt("inventoryType"));
		proHis.setOriginalCost(proObject.getDouble("originalCost"));
		proHis.setOriginalRetailCost(proObject.getDouble("originalRetailCost"));
		proHis.setProdBarCode(proObject.getString("prodBarCode"));
		proHis.setPromotionsCost(proObject.getDouble("promotionsCost"));
		proHis.setPromotionsRetailCost(proObject.getDouble("promotionsRetailCost"));
		proHis.setSalePrice(proObject.getDouble("salePrice"));
		proHis.setSaleType(proObject.getInt("saleType"));
		proHis.setValidTimeStart(proObject.getString("validTimeStart"));
		proHis.setValidTimeEnd(proObject.getString("validTimeEnd"));
	}

	/**
	 * 
	 * @MethodName setProfitsParams
	 * @Description 设置让利参数
	 * @author chengui
	 * @date 2013-7-4 下午4:17:12
	 * @param pro
	 * @param proObject
	 */
	private void setProfitsParams(ProfitsProduct pro, JSONObject proObject) {
		pro.setBrandName(proObject.getString("brandName"));
		pro.setBrandNo(proObject.getString("brandNo"));
		pro.setCasePakgSize(proObject.getString("casePakgSize"));
		pro.setCatName(proObject.getString("catName"));
		pro.setCatNo(proObject.getString("catNo"));
		pro.setCommoName(proObject.getString("commoName"));
		pro.setCommoNo(proObject.getString("commoNo"));
		pro.setInventoryType(proObject.getInt("inventoryType"));
		pro.setOriginalCost(proObject.getDouble("originalCost"));
		pro.setOriginalRetailCost(proObject.getDouble("originalRetailCost"));
		pro.setProdBarCode(proObject.getString("prodBarCode"));
		pro.setPromotionsCost(proObject.getDouble("promotionsCost"));
		pro.setPromotionsRetailCost(proObject.getDouble("promotionsRetailCost"));
		pro.setSalePrice(proObject.getDouble("salePrice"));
		pro.setSaleType(proObject.getInt("saleType"));
		pro.setValidTimeStart(proObject.getString("validTimeStart"));
		pro.setValidTimeEnd(proObject.getString("validTimeEnd"));
		pro.setSelected(1);
	}

	@Override
	public ProfitsProduct getProfitsProductByProductCode(String productCode) {
		return profitsProductDao.findUniqueBy("productCode", productCode);
	}

	@Override
	public List<ProfitsProduct> getProfitsProductList(String code) {
		DetachedCriteria de = profitsProductDao.createCriteria();
		de.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
		de.add(Restrictions.eq("code", code));
		List<ProfitsProduct> pps = profitsProductDao.findByCriteria(de);
		return pps;
	}
	

	@Override
	public ProfitsCommodity getProfitsCommodityByCommoNo(String commodityCode) {
		return profitsCommodityDao.findUniqueBy("commodityCode", commodityCode);
	}

	@Override
	public String getProfitsByProductCode(String productCode) {
		ProfitsProduct pro = null;
		String result = null;
		if(null!= productCode && LogicUtil.isNotNullAndEmpty(productCode))
		{
			DetachedCriteria de = profitsProductDao.createCriteria();
			de.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
			de.add(Restrictions.eq("productCode", productCode));
			List<ProfitsProduct> list = profitsProductDao.findByCriteria(de);
			if(null != list && list.size()>0){
				pro = list.get(0);
				result =String.valueOf(pro.getProfits());
			}
		}
		return result;
	}

	@Override
	@Transactional
	public void getByProductCodeDel(String productCode) throws Exception {
		ProfitsProduct pro = getProfitsProductByProductCode(productCode);
		if(null!=pro){
			profitsProductDao.remove(pro);
		}
	}

	@Override
	public List<BenefitProduct> getProfitsHistory(ProfitsVo vo)
			throws Exception {
		DetachedCriteria criteria = profitsProductHisDao.createCriteria();
		criteria.add(Restrictions.eq("productCode", vo.getProductCode()));
		criteria.add(Restrictions.eq("code", vo.getCode()));
		criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
		List<ProfitsProductHistory> pphs = profitsProductHisDao.findByCriteria(criteria);
		List<BenefitProduct> bps = new ArrayList<BenefitProduct>();
		if (null != pphs && pphs.size() > 0) {
			BenefitProduct bp = null;
			for (ProfitsProductHistory pph : pphs) {
				bp = new BenefitProduct();
				BeanUtils.copyProperties(pph, bp);
				bp.setProdNo(pph.getProductCode());
				bps.add(bp);
			}
		}
		return bps;
	}

	@Override
	public double getProfitsByProductAndTime(String pNo, String time)
			throws Exception {
		DetachedCriteria criteria = profitsProductDao.createCriteria();
		criteria.add(Restrictions.eq("productCode", pNo));
		criteria.add(Restrictions.ge("validTimeEnd", time));
		criteria.add(Restrictions.le("validTimeStart", time));
		criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
		List<ProfitsProduct> pps = profitsProductDao.findByCriteria(criteria);
		ProfitsProduct pp = null;
		if (null != pps && pps.size() > 0) {
			pp = pps.get(0);
		}
		if (null != pp) {
			return pp.getPromotionsCost();
		}
		return -1;
	}

}
